package picture

import (
	"encoding/base64"
	"fmt"
	"github.com/disintegration/imaging"
	"hosptial-record/global"
	"hosptial-record/utils/waterMark"
	"image/color"
	"image/jpeg"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

// GenerateWaterMark 给图片生成水印
func GenerateWaterMark(path string) (img string, err error) {
	isHttp, _ := regexp.MatchString(`^https?://`, path)
	if isHttp {
		img = path
		return img, err
	}
	var dir string
	dir, err = os.Getwd()
	if err != nil {
		return img, err
	}
	// 拼接路劲
	originPath := filepath.Join(dir, path)
	tmpArr := strings.Split(path, "\\")
	fileName := tmpArr[len(tmpArr)-1]
	outputPath := filepath.Join(dir, global.ServerConfig.FilePath, "waterMark", fileName)
	fontPath := filepath.Join(dir, "static", "font", "font.ttf")
	// 目前只处理本地图片
	config := waterMark.TextTiledWatermarkConfig{
		OriginImagePath:    originPath,
		CompositeImagePath: outputPath,
		FontPath:           fontPath,
		Text:               global.ServerConfig.WaterMark,
		Color:              color.RGBA{R: 255, G: 0, B: 0, A: 200},
		TiledRows:          3, // 平铺行数
		TiledCols:          4, // 平铺列数
	}
	err = waterMark.CreateTextTiledWatermark(config)
	if err != nil {
		fmt.Println("添加水印失败:", err)
		return img, err
	}
	img, err = ImageToBase64(outputPath)
	// 需要格式换进行处理
	tmpArr = strings.Split(outputPath, ".")
	extra := tmpArr[len(tmpArr)-1]
	img = fmt.Sprintf("data:image/%s;base64,%s", extra, img)
	// 转换完成删除本地文件
	if err := os.Remove(outputPath); err != nil {
		return "", err
	}
	return img, err
}

// ImageToBase64 图片转base64
func ImageToBase64(filePath string) (string, error) {
	// 打开图像文件
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// 读取图像内容到内存中
	imgData, err := os.ReadFile(filePath) // 或者使用 ioutil.ReadAll(file) 在 Go 1.15 以下版本
	if err != nil {
		return "", err
	}

	// 将图像数据编码为Base64字符串
	base64Str := base64.StdEncoding.EncodeToString(imgData)
	return base64Str, nil
}

func CompressImage(inputPath, outputPath string, quality int) error {
	fmt.Println(inputPath)
	img, err := imaging.Open(inputPath)
	if err != nil {
		return err
	}

	// 调整图片质量
	out, err := os.Create(outputPath)
	if err != nil {
		return err
	}
	defer out.Close()

	return jpeg.Encode(out, img, &jpeg.Options{Quality: quality})
}
